import { useRequest } from "../../../utils/request";
import { bindUserInfo } from "../../../service/user";

Component({
    properties: {},
    data: {
        status: 0,
        _map: {
            0: 'food',
            1: 'scene',
            2: 'house'
        }
    },
    observers: {
        'userInfo.**': function (data) {
            if (data) {
                this.getRequest.run({
                    house_user_id: data.house_user_id
                })
            }
        }
    },
    methods: {
        onLoad() {
            this.getRequest = new useRequest('api/houseownerinfo', {
                hold: true,
                data: 'data',
                pretreatment: data => {
                    return data.house_introduce
                }
            }, this)
            this.setRequest = new useRequest('api/houseintroduce', { hold: true, loading: 'setLoading' }, this)

            bindUserInfo(this)
        },
        textInput(e) {
            const { type, index, key } = e.currentTarget.dataset
            this.setData({
                [`data.${type}[${index}].${key}`]: e.detail.value
            })
        },
        changeStatus(e) {
            const index = Number(e.detail.index)
            this.setData({
                status: index
            })
        },
        add() {
            const name = this.data._map[this.data.status]
            this.setData({
                [`data.${name}`]: [...this.data.data[name], {}]
            })
        },
        del(e) {
            const { type, index } = e.currentTarget.dataset
            const data = [...this.data.data[type]]
            data.splice(index, 1)
            this.setData({
                [`data.${type}`]: data
            })
        },
        submit() {
            if (this.data.data.food.some(item => !item.name || !item.address)) {
                wx.showToast({
                    icon: 'none',
                    title: '请完成特色美食的内容'
                })
                return
            }

            if (this.data.data.scene.some(item => !item.name || !item.address)) {
                wx.showToast({
                    icon: 'none',
                    title: '请完成风土景点的内容'
                })
                return
            }

            if (this.data.data.house.some(item => !item.title || !item.content)) {
                wx.showToast({
                    icon: 'none',
                    title: '请完成房屋内部的内容'
                })
                return
            }

            this.setRequest.run({
                house_introduce: this.data.data
            }).then(() => {
                wx.showToast({
                    title: '保存成功',
                })
            })
        }
    }
});
